package br.megareleased.tvshow;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.appwork.utils.event.Eventsender;

import br.megareleased.model.Episode;
import br.megareleased.model.Series;
import br.megareleased.tvdb.TheTVDB;

class SerieControllerBroadcaster extends Eventsender<SerieControllerListener, SerieControllerEvent> {

    @Override
    protected void fireEvent(final SerieControllerListener listener, final SerieControllerEvent event) {
        listener.onSerieControllerEvent(event);
    }
}

public class SerieController implements SerieControllerListener, SerieControllerInterface {

    private transient SerieControllerBroadcaster broadcaster = new SerieControllerBroadcaster();
	private Set<Episode> episodeList = new HashSet<Episode>();
    private static SerieController INSTANCE = new SerieController();

    public static SerieController getInstance() {
        return INSTANCE;
    }

    private SerieController() {
        broadcaster.addListener(this);
    }

    public void addListener(final SerieControllerListener l) {
        broadcaster.addListener(l);
    }

    public void removeListener(final SerieControllerListener l) {
        broadcaster.removeListener(l);
    }

	@Override
	public void addEpisode(Episode... e) {
		for (Episode episode : e) {
			if(this.episodeList.add(episode)) {
				//episode.addURL(new GetLink(message.getLink()).getMegaUploadLink()); //TODO PEGAR LINK
				broadcaster.fireEvent(new SerieControllerEvent(this, SerieControllerEvent.ADD_EPISODE, episode));
			}
		}
	}

	@Override
	public void removeEpisode(Episode... sl) {
	}
	
	@Override
	public Episode parse(String arg) {
		Pattern p = Pattern.compile("(.*?)[.\\s][sS](\\d{2})[eE](\\d{2}).*");
		Matcher m = p.matcher(arg);
		if (m.matches()) {
			TheTVDB theTVDB = new TheTVDB();
			List<Series> series = theTVDB.searchSeries(m.group(1), "en");
			if(series.size() > 0) {
				Series serie = series.get(0);
				Episode episode = theTVDB.getEpisode(serie.getId(), Integer.parseInt(m.group(2)), Integer.parseInt(m.group(3)), "en");
				
				if(episode != null) { 
					episode.setSerie(serie);
					addEpisode(episode);
				}
			}
		}
		
		return null;
	}
	
	public Set<Episode> getEpisodeList() {
		return episodeList;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onSerieControllerEvent(SerieControllerEvent event) {
	    switch (event.getEventID()) {
        case SerieControllerEvent.ADD_EPISODE:
        }
	}
}
